<?php
namespace app\controller\admin\cms;

use app\BaseController;
use app\model\cms\NavModel;
use think\facade\Request;

class Nav extends BaseController{


    public function index(){

    
        $uniacid = current_uni_account();

        $list = NavModel::where( 'uniacid', $uniacid )->order('id', 'asc')->select();

        foreach( $list as &$nav ){

            $nav['parent'] = NavModel::where( 'id', $nav->pid )->find();
            
        }

        return json( $list );
    }

    

    public function single(){

        $id = $_GET['id'];

        $nav = NavModel::where( 'id', $id )->find();

        $nav['parent'] = NavModel::where( 'id',$nav->pid )->find();

        return json($nav) ;

    }



    public function remove( Request $request ){

        $res= [
            'code'=>0,
        ];

        $id = Request::param( 'id' );
        if( empty( $id ) ){

            $res= [
                'code'=>1,
                'message'=>'请选中你要删除的导航',
            ];
            return json( $res );

            
        }

        //todo 查看是否有子分类，有则报错
        $child = NavModel::hasChild( $id );

        if( !empty($child) ){

            $res['code'] = 1;
            $res['id'] = $id;
            $res['message'] = '导航下有子导航,无法删除';
        }else{

            //todo 删除导航
            $res['ret'] = NavModel::where( 'id',$id )->delete();
        }

        return json( $res );

    }


    public function edit(){

        $id = $_GET['id'];

        // $parent_id = $_POST['parent_id'];

        $title = $_POST['title'];
        $sort_order = $_POST['sort_order'];
        $status = $_POST['status'];
        $link = $_POST['link'];
        $pid = $_POST['pid'];
        $bottom = isset($_POST['bottom']) ? intval($_POST['bottom']) : 0;
        // $image = $_POST['image'];


        $res['code'] = 0;
        $uniacid = current_uni_account();
        $data = [
            'uniacid'   => $uniacid,
            'title'     => $title,
            'sort_order'=> $sort_order,
            'status'    => $status,
            'link'      => $link,
            'pid'       => $pid,
            'bottom'    => $bottom,
        ];
        //todo 修改 nav

        if( $id ){
            $res['ret'] = NavModel::update(  $data,[ 'id' => $id ] );
        }else{
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['updated_at'] = date('Y-m-d H:i:s');
            $res['ret'] = NavModel::create( $data );
        }

        
        
        $res['id'] = $id;
        return json( $res );

    }

}